package com.springboot.myboot.controller;

import com.springboot.myboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class UserController {
    private static File userDir;

    static {
        userDir = new File("./users");
        if (!userDir.exists()) {
            userDir.mkdirs();
        }
    }

    @RequestMapping("/myweb/reg")
    //传参方式3
    public void reg(User user, HttpServletResponse response) {
        if(user.getUsername()==null||user.getPassword()==null||
                user.getNickname()==null||user.getUsername().isEmpty()||
                user.getPassword().isEmpty()||user.getNickname().isEmpty()){
            try {
                response.sendRedirect("/myweb/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        File userFile = new File(userDir,user.getUsername()+".obj");
        if(userFile.exists()){//文件存在则说明是重复用户
            try {
                response.sendRedirect("/myweb/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        try (
                FileOutputStream fos = new FileOutputStream(userFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);
            response.sendRedirect("/myweb/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }


